//
//  PhoneViewController.m
//  LPSNews
//
//  Created by Ruan on 14-10-23.
//  Copyright (c) 2014年 LPS. All rights reserved.
//



#import "PhoneViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "techMode.h"
#import "TechTableViewCell.h"
#import "MJRefresh.h"
#import "TechDetailViewController.h"
#import "PhotoViewController.h"


#define phoneURLString @"http://c.m.163.com/nc/article/list/T1348649654285/"

static int pageNumber = 20;
@interface PhoneViewController ()

@property (nonatomic, retain) NSMutableArray * phoneContentArray;
@property (nonatomic, retain)AFHTTPRequestOperationManager *requestManager;
@end

@implementation PhoneViewController

-(void)dealloc
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self.requestManager.operationQueue cancelAllOperations];
    [_phoneContentArray release];
    [super dealloc];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.tableView addHeaderWithTarget:self action:@selector(headerUpdata)];
    [self.tableView addFooterWithTarget:self action:@selector(footUpdata)];
    
}

- (void)headerUpdata
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString *headerUpdataString = [phoneURLString stringByAppendingFormat:@"%d-20.html",0];
        [self requestWebDataForURLString:headerUpdataString andIsDowndrag:YES];
    });
    
}

- (void)footUpdata
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString *footUpdataString = [phoneURLString stringByAppendingFormat:@"%d-20.html",pageNumber];
        [self requestWebDataForURLString:footUpdataString andIsDowndrag:NO];
    });
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _phoneContentArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *techCellStr = @"PhoneCell";
    
    TechTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:techCellStr];
    
    if (cell == nil) {
        
        cell = [[[TechTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:techCellStr] autorelease];
    }
    cell.techcellImageView.image = nil;
    cell.techcellTitle.text = nil;
    cell.techcellAccessibilityLabel.text = nil;
    cell.techcellSencondImageView.image = nil;
    cell.techcellThreeImageView.image = nil;
    cell.techBottomLine.backgroundColor = [UIColor clearColor];
    cell.tableRow = indexPath.row;
    TechMode *techData = _phoneContentArray[indexPath.row];
    
    cell.techMode = techData;
    
    return cell;
}

- (void) tableViewDownLoadDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag
{
    if (_phoneContentArray == nil) {
        
        _phoneContentArray = [[NSMutableArray alloc] init] ;
        
        [self requestWebDataForURLString:urlstring andIsDowndrag:isDowndrag];
    }
}


- (void)requestWebDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag

{
    NSMutableArray *requestDataArray = [[NSMutableArray alloc] init];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    self.requestManager = requestManager;
    [requestManager GET:urlstring  parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dict = responseObject;
        NSArray *keyarray = [dict allKeys];
        NSString *keyString = keyarray[0];
        NSArray *techArray = [dict objectForKey:keyString];
        
        for (NSDictionary *dict in techArray) {
            TechMode *tech = [[TechMode alloc] init];
            [tech setValuesForKeysWithDictionary:dict];
            [requestDataArray addObject:tech];
            [tech release];
        }
        if (isDowndrag) {
            
            self.phoneContentArray = requestDataArray;
            [self.tableView headerEndRefreshing];
            pageNumber = 20;
            
        }else
        {
            [self.phoneContentArray addObjectsFromArray:requestDataArray];
            pageNumber += 20;
            [self.tableView footerEndRefreshing];
        }
        
        [self.tableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        UILabel *textLable = [[UILabel alloc] init];
        textLable.frame = CGRectMake(0, 0, 140, 100);
        textLable.center = CGPointMake(160, 240);
        textLable.backgroundColor = [UIColor darkGrayColor];
        textLable.text = @"网络不给力";
        textLable.textColor = [UIColor whiteColor];
        textLable.textAlignment = NSTextAlignmentCenter;
        textLable.layer.cornerRadius = 8;
        textLable.layer.masksToBounds = YES;
        [self.view.window addSubview:textLable];
        textLable.alpha = 0;
        [UIView animateWithDuration:0.1 animations:^{
            [UIView animateWithDuration:0.1 delay:0.2 options:UIViewAnimationOptionCurveLinear animations:^{
                textLable.alpha = 0.8;
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.5 delay:1 options:UIViewAnimationOptionCurveLinear animations:^{
                    textLable.alpha = 0;
                } completion:^(BOOL finished) {
                    [textLable removeFromSuperview];
                }];
            }];
        }];
        
        [textLable release];
        
        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
        
    }];
    
    [requestDataArray release];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    TechMode *techData = self.phoneContentArray[indexPath.row];
    
    if (indexPath.row == 0) {
        return 210;
    } if (techData.imgextra != nil) {
        return 116;
    }
    return 85;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TechMode *techData = _phoneContentArray[indexPath.row];
    
    if (techData.photosetID == nil) {
        TechDetailViewController *techDetail = [[TechDetailViewController alloc] init];
        [self.navigationController pushViewController:techDetail animated:NO];
        
        techDetail.docid = techData.docid;
        
        [techDetail release];
    }
    else
    {
        PhotoViewController *photoDetail = [[PhotoViewController alloc] init];
        
        photoDetail.photosetID = techData.photosetID;
        [self.navigationController pushViewController:photoDetail animated:YES];
        
        [photoDetail release];
    }

    
}
@end